using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.bankaccounts;
using System.ComponentModel;
using SupplierCustomerManagement.Domain.Enums;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.bankaccounts
{
    /// <summary>
    /// 获取银行账户列表查询处理器
    /// </summary>
    public class GetBankAccountsQueryHandler : IRequestHandler<GetBankAccountsQuery, ApiPaging<BankAccountListDto>>
    {
        private readonly IBaseRepository<BankAccount> _bankAccountRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetBankAccountsQueryHandler> _logger;

        public GetBankAccountsQueryHandler(
            IBaseRepository<BankAccount> bankAccountRepository,
            IMapper mapper,
            ILogger<GetBankAccountsQueryHandler> logger)
        {
            _bankAccountRepository = bankAccountRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取银行账户列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页查询结果</returns>
        public async Task<ApiPaging<BankAccountListDto>> Handle(GetBankAccountsQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询银行账户列表，页码: {PageIndex}, 每页大小: {PageSize}", 
                    request.PageIndex, request.PageSize);

                // 构建查询条件
                var query = _bankAccountRepository.GetAll()
                    .Where(ba => !ba.IsDeleted); // 排除已删除的记录

                // 应用筛选条件
                query = ApplyFilters(query, request);

                // 获取总数量
                var totalCount = await query.CountAsync(cancellationToken);

                // 计算总页数
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);

                // 分页查询
                var bankAccounts = await query
                    .OrderByDescending(ba => ba.CreatedTime) // 按创建时间倒序排列
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 映射到DTO
                var bankAccountDtos = _mapper.Map<List<BankAccountListDto>>(bankAccounts);

                // 添加枚举描述
                foreach (var dto in bankAccountDtos)
                {
                    dto.RelatedEntityTypeDescription = GetEnumDescription(dto.RelatedEntityType);
                    dto.AccountTypeDescription = GetEnumDescription(dto.AccountType);
                    dto.AccountPropertyDescription = GetEnumDescription(dto.AccountProperty);
                    dto.AccountRelationshipTypeDescription = dto.AccountRelationshipType.HasValue 
                        ? GetEnumDescription(dto.AccountRelationshipType.Value) 
                        : null;
                }

                _logger.LogInformation("成功查询银行账户列表，总数量: {TotalCount}, 当前页数量: {CurrentPageCount}", 
                    totalCount, bankAccountDtos.Count);

                return new ApiPaging<BankAccountListDto>
                {
                    code = ResultEnumCode.Ok,
                    message = "查询成功",
                    data = default,
                    TotalCount = totalCount,
                    PageCount = pageCount,
                    PageData = bankAccountDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询银行账户列表时发生异常");
                
                return new ApiPaging<BankAccountListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询银行账户列表时发生异常: {ex.Message}",
                    data = default,
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<BankAccountListDto>()
                };
            }
        }

        /// <summary>
        /// 应用筛选条件
        /// </summary>
        /// <param name="query">查询对象</param>
        /// <param name="request">查询请求</param>
        /// <returns>应用筛选条件后的查询对象</returns>
        private IQueryable<BankAccount> ApplyFilters(IQueryable<BankAccount> query, GetBankAccountsQuery request)
        {
            // 关联实体ID筛选
            if (request.RelatedEntityId.HasValue)
            {
                query = query.Where(ba => ba.RelatedEntityId == request.RelatedEntityId.Value);
            }

            // 关联实体类型筛选
            if (request.RelatedEntityType.HasValue)
            {
                query = query.Where(ba => ba.RelatedEntityType == request.RelatedEntityType.Value);
            }

            return query;
        }

        /// <summary>
        /// 获取枚举描述
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <returns>枚举描述</returns>
        private string GetEnumDescription(Enum enumValue)
        {
            var field = enumValue.GetType().GetField(enumValue.ToString());
            if (field != null)
            {
                var attribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false)
                    .FirstOrDefault() as DescriptionAttribute;
                return attribute?.Description ?? enumValue.ToString();
            }
            return enumValue.ToString();
        }
    }
}